package com.woniuxy.filter;

import com.woniuxy.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;
import java.util.Set;

//@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    /**
     * 认证中心url
     */
    private static final String AUTH_URL = "http://192.168.1.29:8061/login/loginUI";
    /**
     * 当前网关的url
     */
    private static final String GATEWAY_URL = "http://192.168.1.29:8000";

    /**
     * 过滤器
     *
     * @param exchange web服务交换机
     * @param chain 网关过滤链
     * @return  事务
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        // 统一鉴权逻辑
//        String token = exchange.getRequest().getQueryParams().getFirst("token");
//        if (StringUtils.isEmpty(token)) {
//            // 认证失败
//            System.out.println("认证失败");
//            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);//设置响应码为未授权编码
//            return exchange.getResponse().setComplete();
//        }
//        return chain.filter(exchange);

        //获取请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //从cookie中获取token
        String tokenC = null;

        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        Set<Map.Entry<String, List<HttpCookie>>> entries = cookies.entrySet();
        for (Map.Entry<String, List<HttpCookie>> entry : entries) {
            if ("token".equals(entry.getKey())) {
                List<HttpCookie> value = entry.getValue();
                if (value.size() > 0) {
                    tokenC = value.get(0).getValue();
                }
            }
        }

        //从请求中获取token
        String tokenR = request.getQueryParams().getFirst("token");
        //优先使用请求中的token
        String token = tokenR != null ? tokenR : tokenC;

        //获取返回时的url
        String backUrl = GATEWAY_URL + request.getPath().toString();
        log.error("返回时的URL:{}",request.getPath().toString());

        //判断是否携带token
        if (!StringUtils.isEmpty(tokenR)) {
            //校验token
            boolean b = JwtUtils.verifyToken(token);
            if (b) {
                //校验通过，放行
                return chain.filter(exchange);
            } else {
                //校验不通过，重定向到认证中心登录
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().set(HttpHeaders.LOCATION, AUTH_URL + "?backUrl=" + backUrl);
                return exchange.getResponse().setComplete();
            }
        } else {
            //没有携带token,重定向到认证中心登录
            response.setStatusCode(HttpStatus.SEE_OTHER);
            response.getHeaders().set(HttpHeaders.LOCATION, AUTH_URL + "?backUrl=" + backUrl);
            return exchange.getResponse().setComplete();
        }
    }

    /**
     *标识当前过滤器的优先级，返回的数字越小，优先级越高
     *
     * @return int 优先级级别
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
